<?php

namespace Xin\Menu;

class Util
{
	/**
	 * 遍历树形数据
	 *
	 * @param array $menus
	 * @param callable $callback
	 * @param mixed $parent
	 * @return array
	 */
	public static function eachTree(array &$menus, callable $callback, &$parent = null)
	{
		foreach ($menus as &$menu) {
			call_user_func_array($callback, [&$menu, &$parent]);
			if (isset($menu['child'])) {
				self::eachTree($menu['child'], $callback, $menu);
			}
		}
		unset($menu);

		return $menus;
	}

	/**
	 * 遍历过滤菜单
	 *
	 * @param array $menus
	 * @param callable $callback
	 * @return array
	 */
	public static function eachTreeFilter(array $menus, callable $callback)
	{
		foreach ($menus as $key => &$menu) {
			if (call_user_func_array($callback, [$menu]) === false) {
				unset($menus[$key]);
			} elseif (isset($menu['child'])) {
				$menu['child'] = self::eachTreeFilter($menu['child'], $callback);
			}
		}
		unset($menu);

		return $menus;
	}
}
